<!-- pages/historyManage/historyManage.vue -->
<template>
  <view class="history-manage-container">
    <!-- 操作栏 -->
    <view class="operation-bar">
      <uni-search-bar 
        placeholder="搜索历史标题或内容" 
        v-model="searchKey"
        @confirm="loadData(true)"
        cancel-button="none"
      />
      <view class="filter-row">
        <picker mode="date" @change="dateFilterChange">
          <view class="filter-btn">
            时间筛选
            <uni-icons type="calendar" size="14" color="#666"/>
          </view>
        </picker>
        <button class="add-btn" @tap="showEditForm(null)">+ 新建历史</button>
      </view>
    </view>

    <!-- 数据统计 -->
    <scroll-view class="stats-scroll" scroll-x>
      <view class="stats-card">
        <text class="stats-value">{{ total }}</text>
        <text class="stats-label">总记录数</text>
      </view>
      <view class="stats-card">
        <text class="stats-value">{{ todayCount }}</text>
        <text class="stats-label">今日新增</text>
      </view>
      <view class="stats-card">
        <text class="stats-value">{{ verifiedCount }}</text>
        <text class="stats-label">已审核</text>
      </view>
    </scroll-view>

    <!-- 历史列表 -->
    <scroll-view 
      class="history-list"
      scroll-y
      @scrolltolower="loadMore"
    >
      <view 
        v-for="item in showList"
        :key="item.id"
        class="history-item"
      >
        <view class="header">
          <text class="title">{{ item.title }}</text>
          <uni-tag 
            :text="item.status | statusText"
            :type="item.status | statusType"
            size="small"
          />
        </view>
        
        <view class="content">
          <text class="text">{{ item.content }}</text>
        </view>

        <view class="footer">
          <text class="time">{{ item.createTime | formatDate }}</text>
          <view class="actions">
            <button class="btn edit" @tap="showEditForm(item)">编辑</button>
            <button 
              class="btn status" 
              :class="item.status ? 'disable' : 'enable'"
              @tap="toggleStatus(item)"
            >
              {{ item.status ? '归档' : '激活' }}
            </button>
            <button 
              class="btn delete" 
              @tap="deleteHistory(item)"
              v-if="adminInfo.role === '超级管理员'"
            >删除</button>
          </view>
        </view>
      </view>

      <!-- <uni-load-more :status="loadingStatus"/> -->
    </scroll-view>

    <!-- 编辑弹窗 -->
    <uni-popup ref="editPopup" type="dialog">
      <uni-popup-dialog 
        mode="form" 
        :title="editForm.id ? '编辑历史' : '新建历史'"
        @confirm="submitForm"
      >
        <uni-forms :model="editForm">
          <uni-forms-item label="历史标题" required>
            <uni-easyinput v-model="editForm.title" placeholder="请输入标题"/>
          </uni-forms-item>
          <uni-forms-item label="详细内容" required>
            <uni-easyinput 
              type="textarea" 
              v-model="editForm.content" 
              placeholder="请输入内容"
              :styles="{height:'300rpx'}"
            />
          </uni-forms-item>
          <uni-forms-item label="时间标识">
            <uni-datetime-picker
              v-model="editForm.timestamp"
              type="datetime"
            />
          </uni-forms-item>
        </uni-forms>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
const generateHistory = (() => {
  let id = 0
  return () => ({
    id: ++id,
    title: `历史事件${id}`,
    content: `这是第${id}条历史记录的示例内容，主要描述某个重要事件的发生过程及其历史意义...`,
    status: Math.random() > 0.3,
    createTime: Date.now() - Math.floor(Math.random()*365*86400000),
    timestamp: Date.now()
  })
})()

export default {
  data() {
    return {
      adminInfo: { role: '超级管理员' },
      searchKey: '',
      filterDate: '',
      loadingStatus: 'more',
      page: 1,
      pageSize: 10,
      historyList: Array.from({length: 8}, generateHistory),
      editForm: this.getDefaultForm()
    }
  },
  computed: {
    total() { return this.historyList.length },
    todayCount() { 
      const today = new Date().setHours(0,0,0,0)
      return this.historyList.filter(h => 
        new Date(h.createTime) >= today
      ).length
    },
    verifiedCount() { return this.historyList.filter(h => h.status).length },
    showList() {
      return this.historyList.filter(h => {
        // 日期筛选
        if(this.filterDate) {
          const date = new Date(h.createTime).toISOString().split('T')[0]
          if(date !== this.filterDate) return false
        }
        // 关键词搜索
        return h.title.includes(this.searchKey) || h.content.includes(this.searchKey)
      }).slice(0, this.page * this.pageSize)
    }
  },
  filters: {
    statusText(value) {
      return value ? '已归档' : '激活中'
    },
    statusType(value) {
      return value ? 'default' : 'success'
    },
    formatDate(timestamp) {
      return new Date(timestamp).toLocaleString()
    }
  },
  methods: {
    getDefaultForm() {
      return {
        id: null,
        title: '',
        content: '',
        timestamp: Date.now(),
        status: false
      }
    },
    dateFilterChange(e) {
      this.filterDate = e.detail.value
      this.page = 1
    },
    showEditForm(item) {
      this.editForm = item ? {...item} : this.getDefaultForm()
      this.$refs.editPopup.open()
    },
    submitForm() {
      if (!this.validateForm()) return
      
      if(this.editForm.id) {
        const index = this.historyList.findIndex(h => h.id === this.editForm.id)
        this.historyList.splice(index, 1, this.editForm)
      } else {
        this.historyList.unshift({
          ...this.editForm,
          id: Date.now(),
          createTime: Date.now()
        })
      }
      this.$refs.editPopup.close()
      uni.showToast({ title: '操作成功' })
    },
    validateForm() {
      if(!this.editForm.title.trim()) {
        uni.showToast({ title: '请输入历史标题', icon: 'none' })
        return false
      }
      if(this.editForm.content.length < 10) {
        uni.showToast({ title: '内容至少需要10个字', icon: 'none' })
        return false
      }
      return true
    },
    toggleStatus(item) {
      item.status = !item.status
    },
    deleteHistory(item) {
      uni.showModal({
        title: '确认删除',
        content: '确定要永久删除该历史记录吗？',
        success: (res) => {
          if(res.confirm) {
            this.historyList = this.historyList.filter(h => h.id !== item.id)
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.history-manage-container {
  padding: 20rpx;
}

.operation-bar {
  background: white;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;

  .filter-row {
    display: flex;
    gap: 20rpx;
    margin-top: 20rpx;

    .filter-btn {
      flex: 1;
      padding: 10rpx 20rpx;
      background: #f8f9fa;
      border-radius: 8rpx;
    }

    .add-btn {
      background: #3498db;
      color: white;
      padding: 10rpx 20rpx;
    }
  }
}

.stats-scroll {
  white-space: nowrap;
  margin-bottom: 20rpx;

  .stats-card {
    display: inline-block;
    background: white;
    padding: 30rpx 50rpx;
    border-radius: 16rpx;
    margin-right: 20rpx;

    .stats-value {
      font-size: 40rpx;
      font-weight: bold;
      color: #2ecc71;
    }

    .stats-label {
      font-size: 28rpx;
      color: #7f8c8d;
    }
  }
}

.history-list {
  height: calc(100vh - 440rpx);
}

.history-item {
  background: white;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15rpx;

    .title {
      font-size: 32rpx;
      font-weight: 500;
      color: #2c3e50;
    }
  }

  .content {
    .text {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3;
      overflow: hidden;
    }
  }

  .footer {
    margin-top: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .time {
      font-size: 24rpx;
      color: #95a5a6;
    }

    .actions {
      display: flex;
      gap: 10rpx;

      .btn {
        padding: 8rpx 20rpx;
        font-size: 26rpx;

        &.edit { background: #f1c40f; }
        &.enable { background: #2ecc71; }
        &.disable { background: #e74c3c; }
        &.delete { background: #95a5a6; }
      }
    }
  }
}
</style>